package com.tengju.bff.interfaces.covercharge.job;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tengju.bff.interfaces.covercharge.constant.CertStatusEnum;
import com.tengju.bff.interfaces.covercharge.constant.CustTaskQueueCmdEnum;
import com.tengju.bff.interfaces.covercharge.constant.CustTaskQueueStatusEnum;
import com.tengju.bff.interfaces.covercharge.constant.HeavyKeyEnum;
import com.tengju.bff.interfaces.covercharge.entity.po.CustTaskQueue;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceContractCertificate;
import com.tengju.bff.interfaces.covercharge.entity.vo.CashBackRes;
import com.tengju.bff.interfaces.covercharge.entity.vo.contract.ApplyCertificateStatusResVo;
import com.tengju.bff.interfaces.covercharge.mapper.ServiceContractCertificateMapper;
import com.tengju.bff.interfaces.covercharge.service.ICustTaskQueueService;
import com.tengju.bff.interfaces.covercharge.service.IServiceSelfCertificationWithdrawService;
import com.tengju.bff.interfaces.covercharge.service.bestsign.impl.contract.BestSignApplyCertService;
import com.tengju.bff.interfaces.covercharge.util.DateTimeUtils;
import com.tengju.bff.interfaces.covercharge.util.MqTimeUtil.CertApplyDelayTimeUtil;
import com.tengju.bff.interfaces.covercharge.util.alarmUtil.MsgSendUtil;
import com.tengju.bff.interfaces.covercharge.util.redis.HeavyUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zoi7.component.core.util.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.time.LocalDate;
import java.util.List;

@Component
@Slf4j
public class AutoCheckBestSignStatusJob {

    @Autowired
    private ServiceContractCertificateMapper contractCertificateMapper;
    @Autowired
    private BestSignApplyCertService bestSignApplyCertService;


    @XxlJob("autoCheckBestSignStatusJob")
    public ReturnT<String> execute(String params)  {
        log.info("=autoCheckBestSignStatusJob=开始执行");

        ServiceContractCertificate queryScc = new ServiceContractCertificate();

        List<ServiceContractCertificate> scc = contractCertificateMapper.selectList(new QueryWrapper<>(queryScc)
                .in("status", CertStatusEnum.PROCESSING.getStatus()).ge("create_time", LocalDate.now().minusDays(3)));

        if (!CollectionUtils.isEmpty(scc)) {

            scc.stream().forEach(serviceContractCertificate -> {


                try {
                    {
                        String transId = String.valueOf(UuidUtil.getTimeBasedUuid().toString());
                        ApplyCertificateStatusResVo resVo = bestSignApplyCertService.queryApplyCertStatus(transId,
                                serviceContractCertificate.getAccount(), serviceContractCertificate.getTaskId());

                        String certStatus;
                        String certId = null;
                        String message = "";
                        switch (resVo.getStatus()) {
                            case "-1":
                            case "0":
                            case "3":
                            case "6":
                                //超时-失败重试
                                certStatus = CertStatusEnum.FAILED.getStatus();
                                log.error("证书申请状态-申请失败，需要处理,status:{}", resVo.getStatus());
                                MsgSendUtil.sendLarkMsg("流水号：{},证书申请状态-申请失败，需要处理,status:{}", serviceContractCertificate.getTaskId(), resVo.getStatus());
                                break;
                            case "1":
                            case "2":
                                //申请中-不处理
                                return;
                            case "4":
                                //看错误信息处理
                                certStatus = CertStatusEnum.FAILED.getStatus();
                                message = resVo.getMessage();
                                break;
                            case "5":
                                certStatus = CertStatusEnum.SUCCESS.getStatus();
                                //获取证书编号
                                try {
                                    certId = bestSignApplyCertService.queryApplyCertId(serviceContractCertificate.getBizId(),
                                            serviceContractCertificate.getAccount());
                                } catch (Exception e) {
                                    log.warn("流水号：{},获取证书编号失败", serviceContractCertificate.getBizId());
                                }
                                break;
                            default:
                                certStatus = CertStatusEnum.UNKNOWN.getStatus();
                                break;
                        }
                        ServiceContractCertificate updateInfo = new ServiceContractCertificate();
                        updateInfo.setId(serviceContractCertificate.getId());
                        updateInfo.setStatus(certStatus);
                        updateInfo.setMessage(message);
                        updateInfo.setCertId(certId);
                        updateInfo.setUpdateTime(DateTimeUtils.now());
                        contractCertificateMapper.updateById(updateInfo);


                    }

                } catch (Exception e) {

                    log.error("上上签证书申请状态更新失败", e);
                    MsgSendUtil.sendLarkMsg("上上签证书申请状态更新失败,id_code:%s,task_id:%s", serviceContractCertificate.getIdCode(), serviceContractCertificate.getTaskId());
                }


            });

        }


        log.info("=autoCheckBestSignStatusJob=执行结束");

        return ReturnT.SUCCESS;
    }

}
